use sha2::{Sha256, Digest};
use std::fs::File;
use std::io::{Read, BufReader};
use crate::common::Result;

/// 计算文件的SHA256哈希值
pub fn calculate_file_hash(file_path: &str) -> Result<String> {
    let mut file = File::open(file_path)
        .map_err(|e| crate::common::ManagerError::FileTransferError(format!("无法打开文件: {}", e)))?;
    
    let mut hasher = Sha256::new();
    let mut buffer = [0; 1024];
    
    loop {
        let bytes_read = file.read(&mut buffer)
            .map_err(|e| crate::common::ManagerError::FileTransferError(format!("读取文件失败: {}", e)))?;
        
        if bytes_read == 0 {
            break;
        }
        
        hasher.update(&buffer[..bytes_read]);
    }
    
    let result = hasher.finalize();
    Ok(format!("{:x}", result))
}

/// 计算数据的SHA256哈希值
pub fn calculate_data_hash(data: &[u8]) -> String {
    let mut hasher = Sha256::new();
    hasher.update(data);
    let result = hasher.finalize();
    format!("{:x}", result)
}

/// 验证文件哈希值
pub fn verify_file_hash(file_path: &str, expected_hash: &str) -> Result<bool> {
    let actual_hash = calculate_file_hash(file_path)?;
    Ok(actual_hash == expected_hash)
}

/// 验证数据哈希值
pub fn verify_data_hash(data: &[u8], expected_hash: &str) -> bool {
    let actual_hash = calculate_data_hash(data);
    actual_hash == expected_hash
} 